package net.wanho.listener;

import com.rabbitmq.client.Channel;
import net.wanho.po.Student;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 消费者
 */
@Component
public class MsgListener {

    @RabbitListener(queues = "${shop.queue}")
    public void readMsg(Student stu){
        System.out.println("-------------------------" + stu);
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("queue3"),
            exchange = @Exchange(value = "exchange3.fanout", type = ExchangeTypes.FANOUT)
    ))
    public void readMessage(String msg){
        System.out.println("-------------------------" + msg);
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("queue4"),
            exchange = @Exchange(value = "exchange4.direct", type = ExchangeTypes.DIRECT),
            key = "hello"
    ))
    public void getMessage(String msg, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag) throws IOException {
        System.out.println("读取消息-------------------------" + msg);

        /**
         * 业务处理操作
         */
        // todo.....


        // 确认消息，处理消息成功
        // channel.basicAck(tag, false); // 参数：消息标签、是否批量处理

        // 未确认消息，处理消息失败
        // channel.basicNack(tag, false, true); // 参数：消息标签、是否批量处理、是否重新放入队列

        // 拒绝消息，处理消息失败
        // channel.basicReject(tag, false); // 参数：消息标签、是否重新放入队列

        /**
         * 注意：如果未确认消息或者拒绝消息，且不重新放入列表，此时消息会被丢弃，成为死信！
         */
    }
}
